#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@File Name  : FTP.py
@Author     : LeeCQ
@Date-Time  : 2019/12/17 13:17

curlftpfs ftp://leecq%2Fufile-test:Fp1ta0JPi9hFgBtNgd6J2wnS0VLL08IP@box.u-file.cn/BaiduYun/ /uFile/
"""
import os
from ftplib import FTP
import time


class MyFTP(object):
    remote_file_list = []

    def __init__(self, host='', user='', passwd='', acct='', encode='utf8'):
        self.ftp = FTP(host=host, user=user, passwd=passwd, acct=acct)
        self.set_encoding(encode)

        self.encoding = encode
        self.debug = 0

    def set_debug(self, level):
        self.ftp.set_debuglevel(level)

    def set_encoding(self, encode):
        self.encoding = encode
        self.ftp.encoding = encode

    def set_cwd(self, dir_name):
        return self.ftp.cwd(dir_name)

    def upload(self, remote_path, local_path, block_size=8192):
        """ 上传文件

        :param remote_path: 远程文件
        :param local_path: 本地文件
        :param block_size: 块大小
        :return: 正常返回2开的响应
        """
        with open(local_path, 'rb') as f:  # 读取本地文件
            return self.ftp.storbinary('STOR ' + remote_path, f, block_size)  # storbinary()接收文件句柄
            # 正常返回2开的响应

    def download(self, remote_path, local_path, block_size=8192):
        """以二进制形式下载文件"""
        # local_path = os.path.abspath(local_path)
        with open(local_path, 'wb') as f:  # 写入本地文件
            return self.ftp.retrbinary('RETR ' + remote_path, f.write, block_size)  # 接收write函数
            # 正常返回2开的响应

    @staticmethod
    def __recursion_dir(dir):
        return ['/'.join((dirs, file)).replace('\\', '/') for dirs, _, files in os.walk(dir) for file in files]

    def upload_dir(self, remote_dir: str, local_dir: str):
        """"""
        for file in self.__recursion_dir(local_dir):
            remote_file = file.replace(local_dir, remote_dir).replace('//', '/')
            local_file = file.replace('//', '/')
            self.upload(remote_path=remote_file, local_path=local_file)

    def traversal_remote(self, dir):
        def ttt(dir_):
            try:
                self.ftp.cwd(dir_)
                for d in self.get_dir_nlst('.'):
                    self.traversal_remote(dir_ + '/' + d)
            except:
                self.remote_file_list.append(dir_)

        ttt(dir)

    def download_dir(self, remote_dir, local_dir):
        self.traversal_remote(remote_dir)  # 构建下载列表
        for remote_file in self.remote_file_list:
            local_file = remote_file.replace('\\', '/').replace(remote_dir, local_dir)
            os.makedirs(local_file[:local_file.rfind('/')], exist_ok=True)
            self.download(remote_file, local_file)

    def get_pwd(self):
        return self.ftp.pwd()

    def get_dir_long(self, dir='.'):
        return self.ftp.dir(dir)

    def get_dir_mlsd(self, dir=''):
        return self.ftp.mlsd(dir)

    def get_dir_nlst(self, dir='.'):
        """ Return a list of files in a given directory (default the current).

        :param dir: 目录
        :return: 文件名列表
        """
        return self.ftp.nlst(dir)

    def get_size(self, file_name):
        return self.ftp.size(file_name)

    def get_remote_file_list(self, dir='.'):
        return self.ftp.nlst(dir)

    def __enter__(self):
        """ 上下文管理器 """
        return self

    def __exit__(self, *args):
        try:
            self.ftp.quit()
        except (OSError, EOFError):
            pass
        finally:
            if self.ftp.sock is not None:
                self.ftp.close()


class UFile(MyFTP):
    """U-File自动登录"""
    def __init__(self):
        host = 'box.u-file.cn'
        user = 'leecq/ufile-test'
        passwd = 'Fp1ta0JPi9hFgBtNgd6J2wnS0VLL08IP'
        super().__init__(host=host, user=user, passwd=passwd)


class TEST(MyFTP):
    pass


if __name__ == '__main__':
    host_ = 'box.u-file.cn'
    user_ = 'leecq/ufile-test'
    passwd_ = 'Fp1ta0JPi9hFgBtNgd6J2wnS0VLL08IP'
    start_time = time.time()
    with TEST(host=host_, user=user_, passwd=passwd_) as ftp:
        ftp.ftp.set_debuglevel(1)
        ftp.encoding = 'utf8'
        # print('文件大小', ftp.get_size('/HH/Mzitu/_zip/99955-好刺激啊爆乳肥臀的知性少妇雪千寻扮护士玩SM.zip'))
        # n = ftp.get_dir_long('/HH/Mzitu/_zip')
        n = ftp.get_dir_nlst('.')
        ftp.upload('/HH/test/睡眠革命.mp3', './睡眠革命.MP3')
        # print(n, len(n),)
        print('**', ftp.remote_file_list)
        # ftp.upload_dir(local_dir='/uFile/201135/', remote_dir='/HH/Mzitu/201135/')

    print('[=]OVER ', time.time() - start_time)
